<script setup lang="ts">
import {ref} from "vue";
import {
  projectAll,
  projectPage
} from "@/pages/project/projectManagement/index.js";
import TableTemplate from "@/pages/account/components/tableTemplate.vue";
import {ElMessage} from "element-plus";
import DialogTemplate from "@/pages/account/components/dialogTemplate.vue";
import {useUserStore} from "@/pinia/stores/user";
import {auditProjectAudit, getProjectProgressList, getProjectProgressListIds} from "@/pages/account/accountApi.js";
const loading = ref(false)
const registerDialogRef = ref(null)
const type = ref([])
const statues = [
  {
    value: 0,
    label: '待审核',
  },
  {
    value: 1,
    label: '审核通过',
  },
  {
    value: 2,
    label: '审核不通过',
  }, {
    value: 3,
    label: '驳回',
  },
]
const userStore = useUserStore()
const userData = userStore.userInfo
//表格引用
const registerTableRef = ref(null)
// 弹窗引用
const dialogTemplateRef = ref(null)
// 弹窗引用
const dialogTemplateVisible = ref(false)
const centerDialogVisible = ref(false)
const formDialogVisible = ref(false)
//审核弹窗便签
const activeName = ref('first')
// 弹窗标题引用
const title = ref('')
// 弹窗表单数据
const initialData = ref({})
const formItems = ref([{
  list: [
    {
      label: '项目名称',
      prop: 'title',
      type: 'input',
      rules: [
        {required: true, message: '请输入项目名称', trigger: 'blur'},
        {min: 3, max: 30, message: '长度在 3 到 30 个字符', trigger: 'blur'}
      ],
      placeholder: '请输入项目名称'
    },
    {
      label: '项目负责人',
      prop: 'username',
      type: 'input',
      rules: [
        {required: true, message: '请输入项目负责人', trigger: 'blur'},
        {min: 2, max: 10, message: '长度在 2 到 10 个字符', trigger: 'blur'}
      ],
      placeholder: '请输入项目负责人'
    },
    {
      label: '项目成员',
      prop: 'menber',
      type: 'input',
      rules: [
        {required: true, message: '请输入其他项目成员,多个以英文逗号分隔', trigger: 'blur'},
        {min: 2, max: 40, message: '长度在 2 到 40 个字符', trigger: 'blur'}
      ],
      placeholder: '请输入其他项目成员'
    },
    {
      label: '项目介绍',
      prop: 'content',
      type: 'richText',
    },
    {
      label: '项目类型',
      prop: 'protype',
      type: 'select',
      options: type.value,
      placeholder: '请选择项目类型'
    },
    {
      label: "是否支持下载",
      prop: "download",
      type: "switch",
      value: 0,
    },
    {
      label: '项目图片',
      prop: 'projectImg',
      type: 'uploadImage',
      multiple: true,
      limit: 1,
      rules: [
        {required: true, message: '请上传项目图片', trigger: 'blur'}
      ],
      placeholder: '请上传项目图片'
    },
    {
      label: '项目附件',
      prop: 'file',
      type: 'uploadFile',
      multiple: true,
      limit: 1,
      rules: [
        {required: true, message: '请上传项目附件', trigger: 'blur'}
      ],
      placeholder: '请上传项目附件'
    }
  ]
}])
// 是否查看模式
const isViewMode = ref(false)
// 弹窗提交的数据
const formData = ref({})
// 操作名称
const operationName = ref('')
//选中的行
const handleIndex = ref([])
const handleChange = (data) => {
  handleIndex.value = data
}
//批量新增弹窗引用
let batchAddVisible = reactive({
  fileName: '项目批量新增模板.xlsx',
  dialogFormVisibles: false,
})
//项目状态
const getStatusColor = (statuss) => {
  switch (statuss) {
    case '待审核':
      return 'primary';
    case '审核中':
      return 'success';
    case '审核通过':
      return 'danger';
    case '审核不通过':
      return 'warning';
    default:
      return 'info';
  }
};
const projectTypeAll = async () => {
  //获取项目类型
  let data = await projectAll()
  for (let i = 0; i < data.data.length; i++) {
    type.value.push({
      label: data.data[i].projectType,
      value: data.data[i].id
    });
  }
}
let dataSet = reactive({
  queryBox: [
    {
      model: 'title',
      type: 'input',
      placeholder: '请输入项目名称'
    },
    {
      model: 'username',
      type: 'input',
      placeholder: '项目发起人'
    },
    {
      model: 'type',
      type: 'select',
      placeholder: '项目类型',
      options: type.value,
    },
    {
      model: 'status',
      type: 'select',
      placeholder: '项目状态',
      options: statues,
    }
  ],
  tableList: [
    {prop: 'id', label: '项目ID', width: '80'},
    {prop: 'title', label: '项目名称', width: '180'},
    {prop: 'username', label: '项目发起人', width: '100'},
    {prop: 'protype', label: '项目类型', width: '150'},
    {prop: 'menber', label: '项目成员', width: '180'},
    {prop: 'createTime', label: '创建时间', width: '180'},
  ],
  tnQueryTop: [
    {name: '批量审核', click: 'batchExamine', type: 'primary'},
  ],
  tableListStutas: [
    {prop: 'statuss', label: '项目状态', width: '100', stutasColor: 'danger'},
  ],
  operationBtns: [
    {name: '审核', click: 'examine', type: 'primary'},
    {name: '审核日志', click: 'examineLog', type: 'warning'},
    {name: '详情', click: 'projectDetail', type: 'info'},
  ],
  tableData: {
    total: 0,
    rows: []
  }
})
//查询条件
const selectSubmit = async (data) => {
  loading.value = true;
  data.isSubmit=1;
  if (userData.occupation !==2){
    data.teacherId = userData.id;
  }
  await projectPage(data, data.pageSize, data.pageNum).then(rows=>{
    if (rows.code === 0){
      dataSet.tableData.rows = rows.data.records;
      dataSet.tableData.total = rows.data.total;
    }
  }).finally(() => {
    loading.value = false;
  });

}
// 重置
const resetSubmit = (data) => {
  selectSubmit(data);
}

onMounted(() => {
  selectSubmit({});
  projectTypeAll();
})
const handleSubmit = (data) => {
  console.log(data, 'data')
}

// 批量审核
const batchExamine =async () => {
  if (handleIndex.value.length < 1) {
    ElMessage.error("请选择要审核的项目！")
    return
  }
  initialData.value.reviewer = userData.username
  const ids = handleIndex.value.map(item => item.id)
  // 教师只能审核自己负责的项目，管理员可以审核所有项目
  let isReviewed = false;
  let text = "选择项目中有已审核项目，请勿重复审核！";
  await getProjectProgressListIds(ids).then(res => {
    res.data.forEach(item => {
      //教师是否审核
      if (userData.occupation !==2){
        if (item.reviewer!==null && item.reviewer!==''&& item.auditResult===0){
          isReviewed = true;
          return;
        }
      }
      else {
        //教师是否审核，审核之后才能修改
        if (item.reviewer===null || item.reviewer===''){
          isReviewed = true;
          text="选择的项目中有指导教师未审核项目！";
          return;
        }
        // 教师审核通过才能审核
        else if ((item.modifiedBy===null || item.modifiedBy==='') && item.auditResult!==0){
          isReviewed = true;
          text="该项目指导教师未审核通过！";
          return;
        }
        else if (item.modifiedBy!==null && item.modifiedBy!==''&& item.auditResult===0){
          isReviewed = true;
          return;
        }
      }
    })
  })
  if(isReviewed){
    ElMessage.error(text)
    return;
  }
  operationName.value = "批量审核"
  formDialogVisible.value = true
}
// 审核
const examine = async (data) => {
  operationName.value = "审核"
  initialData.value = {...data}
  // 教师只能审核自己负责的项目，管理员可以审核所有项目
  let isReviewed = false;
  let text = "该项目已审核，请勿重复审核！";
  await getProjectProgressListIds([data.id]).then(res => {
    res.data.forEach(item => {
      //教师是否审核
      if (userData.occupation !==2){
        if (item.reviewer!==null && item.reviewer!=='' && item.auditResult===0){
          isReviewed = true;
        }
      }
      else {
        //教师是否审核，审核之后才能修改
        if (item.reviewer===null || item.reviewer===''){
          isReviewed = true;
          text="该项目指导教师未审核，请等待审核！";
        }
        // 教师审核通过才能审核
        else if ((item.modifiedBy===null || item.modifiedBy==='') && item.auditResult!==0){
          isReviewed = true;
          text="该项目指导教师未审核通过！";
          return;
        }
       else if (item.modifiedBy!==null && item.modifiedBy!==''&& item.auditResult===0){
          isReviewed = true;
        }
      }
    })
  })
  if(isReviewed){
    ElMessage.error(text)
    return;
  }
  initialData.value.reviewer = userData.username
  formDialogVisible.value = true
}
// 详情
const projectDetail = (data) => {
  operationName.value = "详情"
  title.value = '项目详情'
  isViewMode.value = true
  initialData.value = {...data}
  initialData.value.username = userData.username
  dialogTemplateVisible.value = true
  dialogTemplateRef.value.dialogTemplateVisible = true;
}
// 审核日志

const activities = ref([])
const activitiesProgress = ref([])
const examineLog = async (data) => {
  let rows = await getProjectProgressList(data.id);
  activities.value = rows.data.progressList;
  activitiesProgress.value = rows.data.reviewList;
  centerDialogVisible.value = true
}
const handleExamineSubmit = async () => {
  if (initialData.value.active === 1 && userData.occupation === 1){
    ElMessage.error("该项目指导教师还未审核！")
    return;
  }
  let data = {id: initialData.value.id,reviewer: userData.username, person:initialData.value.reviewer,
    reviewerId:userData.id, userId : userData.id, projectName: initialData.value.title,
    reviewComments: initialData.value.remark, auditResult: initialData.value.status, role: userData.occupation === 1?"教师":"管理员"};
  if (operationName.value === "审核"){
    data.projectIds = [initialData.value.id];
  }else {
    let ids = handleIndex.value.map(item => item.id)
    data.projectIds = ids
  }
  await auditProjectAudit(data).then(res => {
    if (res.code === 0) {
      ElMessage.success("审核成功！")
    }
    selectSubmit({})
    formDialogVisible.value = false
  }).catch(err => {
    ElMessage.error("审核失败！")
  });
}
</script>
<template>
  <div>
    <TableTemplate
      ref="registerTableRef"
      :data-set="dataSet"
      @batchExamine="batchExamine"
      @examine="examine"
      @projectDetail="projectDetail"
      @reset-submit="resetSubmit"
      @examineLog="examineLog"
      @handleChange="handleChange"
      @select-submit="selectSubmit"
      :get-status-color="getStatusColor"
      :loading="loading"
    />
    <DialogTemplate
      v-model="dialogTemplateVisible"
      ref="dialogTemplateRef"
      :title="title"
      :width="'800px'"
      @handleDialogSubmit="handleSubmit"
      :initial-data="initialData"
      :form-items="formItems"
      :is-view="isViewMode"
      :operation-name="operationName"
    />
    <el-dialog v-model="centerDialogVisible" title="审核日志" width="700">
        <div>
          <el-tabs v-model="activeName" class="demo-tabs" @tab-click="handleClick">
            <el-tab-pane label="审核进度" name="first">
              <el-timeline style="max-width: 600px;margin-left: 20px;margin-top: 10px">
                <el-timeline-item
                  v-for="(activity, index) in activities"
                  :key="index"
                  :timestamp="activity.role!=='学生'?activity.role+'  审核':activity.role+'  提交'"
                ><span>{{ activity.auditTime }}</span>
                  <br>
                  <span class="span-text" v-if="activity.role!== '学生'">审核结果：{{ activity.auditResult===0?'通过':activity.auditResult===1?'不通过':'驳回' }}</span>
                  <br v-if="activity.role !== '学生'">
                  <span class="span-text"  v-if="activity.role !== '学生'">审核意见：  {{ activity.reviewComments }}</span>
                </el-timeline-item>
              </el-timeline>
            </el-tab-pane>
            <el-tab-pane label="审核步骤" name="second">
              <el-steps style="max-width: 600px" finish-status="success" :active="activitiesProgress.active">
                <el-step title="学生提交审核" :description="activitiesProgress.sTime" />
                <el-step title="教师审核" :description="activitiesProgress.tTime" />
                <el-step title="管理员审核" :description="activitiesProgress.aTime" />
              </el-steps>
            </el-tab-pane>
          </el-tabs>
        </div>
        <template #footer>
          <div class="dialog-footer" style="margin-top: 10px">
            <el-button @click="centerDialogVisible = false">关闭</el-button>
          </div>
        </template>
      </el-dialog>
    <el-dialog v-model="formDialogVisible" title="项目审核" width="700">
        <div>
          <el-form :model="initialData" label-width="auto" style="max-width: 500px">
            <el-form-item v-if="operationName === '审核'" label="项目名称">
              <el-input :disabled="true" v-model="initialData.title" />
            </el-form-item>
            <el-form-item v-if="operationName === '审核'" label="项目负责人">
              <el-input :disabled="true" v-model="initialData.username" />
            </el-form-item>
            <el-form-item label="审核人">
              <el-input :disabled="true" v-model="initialData.reviewer" />
            </el-form-item>
            <el-form-item label="审核结果">
              <el-radio-group v-model="initialData.status">
                <el-radio label="通过" :value=0>通过</el-radio>
                <el-radio label="驳回" :value=1>不通过</el-radio>
                <el-radio label="驳回" :value=2>驳回</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="审核意见">
              <el-input v-model="initialData.remark" type="textarea" autosize
                        :rows="3" show-word-limit maxlength="300"/>
            </el-form-item>
          </el-form>
        </div>
        <template #footer>
          <div class="dialog-footer" style="margin-top: 10px">
            <el-button @click="formDialogVisible = false">关闭</el-button>
            <el-button type="primary" @click="handleExamineSubmit">提交</el-button>
          </div>
        </template>
      </el-dialog>
  </div>
</template>

<style scoped lang="scss">
.span-text{
  font-size: 14px;
  color: darkseagreen;
}
</style>
